// eslint-disable-next-line import/named
import { MutationTree } from 'vuex'
import { AppWidgetData, Widget, WidgetStateInterface } from './state'

const mutation: MutationTree<WidgetStateInterface> = {

  setApps (state, apps) {
    state.apps = apps
  },

  removeMultiApps (state, apps: AppWidgetData[]) {
    apps.forEach((e) => {
      state.apps = state.apps.filter(v => v.id !== e.id)
    })
  },

  updateApp (state, updateSet) {
    const matchApp = state.apps.find(e => e.id === updateSet.id)
    if (matchApp) {
      Object.assign(matchApp, updateSet)
    } else {
      throw Error('Mutation updateApp Fail.')
    }
    const matchWidget = state.widgets.find(e => e.apps?.find(e => e.id === updateSet.id))
    if (matchWidget) {
      matchWidget.apps = matchWidget.apps || []
      const matchWidgetApp = matchWidget.apps.find(e => e.id === updateSet.id)
      Object.assign(matchWidgetApp, updateSet)
    }
  },

  setWidgets (state, widgets) {
    state.widgets = widgets
  },

  updateWidget (state, widget) {
    const matchWidget = state.widgets.find(e => e.id === widget.id)
    if (matchWidget) {
      Object.assign(matchWidget, widget)
    }

    // [?] AppGroupWidget GridLayout apps length=0 问题
    // 在被销毁前会发送一个 updated-layout
    // 此时组件数据已经不在 state.widgets 上存在
  },

  updateWidgets (state, widgets: Widget[]) {
    state.widgets.forEach((appLayout, index) => {
      const newWidget = widgets.find(e => e.id === appLayout.id)
      if (JSON.stringify(newWidget) !== JSON.stringify(state.widgets[index])) {
        Object.assign(state.widgets[index], newWidget)
      }
    })
  },

  createWidget (state, widget: Widget) {
    const matchWidget = state.widgets.find(e => e.id === widget.id)
    if (matchWidget) {
      throw Error('Mutation createWidget fail, found same id widget')
    }
    state.widgets = [
      ...state.widgets,
      widget
    ]
  },

  deleteWidget (state, widget: Widget) {
    state.widgets = state.widgets.filter(e => e.id !== widget.id)
  },

  setCollectionApps (state, apps) {
    state.collectionApps = apps || []
  },

  setOptions (state, options) {
    state.options = options
  },

  setInitialized (state) {
    state.options.initialized = true
  }
}

export default mutation
